<template>
  <router-view v-if="route.matched.length === 3" @updated="handleProgressUpdated" />
  <e-container v-else>
    <div class="operations">
      <a-space>
        <e-title title="Phase Progress" />
        <a-divider type="vertical" />
        <!-- 正常的非二开用户或者二开后已经重启Phase的用户的用户可以添加记录，leadStatus === 0 代表当前的Phase是活跃的 --->
        <a-button
          v-if="leadStatus === 0 && !revivalClientNeedRestart"
          v-permission="'PhaseProgress:Add'"
          type="link"
          size="small"
          @click="() => router.push({ name: 'Add Communication Record', params: { id: id, action: 'add' } })"
        >
          <a-space>
            <e-icon type="add" />
            Add Communication Record
          </a-space>
        </a-button>
        <a-button
          v-if="leadStatus === 0"
          v-permission="'PhaseProgress:Restart'"
          type="link"
          size="small"
          style="color: #ff9a17"
          @click="() => router.push({ name: 'Add Communication Record', params: { id: id, action: 'restart' } })"
        >
          <a-space>
            <e-icon type="restart" />
            Restart
          </a-space>
        </a-button>
      </a-space>
      <a-space class="buttons" :size="40">
        <a-button
          v-if="canTransit === true && leadStatus === 0"
          v-permission="'PhaseProgress:Transit'"
          class="secondary"
          @click="handleTransit(false)"
        >
          Transit
        </a-button>
        <div v-if="clientIsNoPhase || leads.length > 0" v-permission="'PhaseProgress:Query:History'">
          <a-dropdown>
            <a-button type="primary">
              <a-space>
                Other Records
                <e-icon type="Unfold" />
              </a-space>
            </a-button>
            <template #overlay>
              <a-menu v-model:selectedKeys="leadIdForMenu" @click="handleChangeLead">
                <!-- 第一条并且是活跃的显示为current -->
                <a-menu-item v-if="revivalClientNeedRestart" :key="-1" :status="1">Restart Phase</a-menu-item>
                <a-menu-item v-if="clientIsNoPhase" :key="-1" :status="1">Activate Client</a-menu-item>
                <a-menu-item v-for="(lead, index) in leads" :key="lead.value" :status="lead.status">
                  {{ index === 0 && lead.status === 0 ? 'Current' : lead.text }}
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </a-space>
    </div>
    <!-- 是目标客户但是phaseID是-1 -->
    <div v-if="clientIsNoPhase && leadId < 0" v-permission="'PhaseProgress:Query'" class="activate-client">
      <a-tag>Phase 0</a-tag>
      <a-button
        v-permission="'PhaseProgress:Add'"
        type="link"
        size="small"
        @click="() => router.push({ name: 'Add Communication Record', params: { id: id, action: 'activate' } })"
      >
        <a-space>
          <e-icon type="add" />
          Activate by Adding Communication Record
        </a-space>
      </a-button>
    </div>
    <!-- 二次开发且还未重启Phase -->
    <div
      v-else-if="revivalClientNeedRestart && leadId < 0"
      v-permission="'PhaseProgress:Query'"
      class="activate-client"
    >
      <a-tag class="revival">Revival</a-tag>
      <a-button
        v-permission="'PhaseProgress:Add'"
        type="link"
        size="small"
        @click="() => router.push({ name: 'Add Communication Record', params: { id: id, action: 'restart' } })"
      >
        <a-space>
          <e-icon type="add" />
          Restart by Adding Communication Record
        </a-space>
      </a-button>
    </div>
    <a-spin v-else v-permission="'PhaseProgress:Query'" :spinning="processLoading">
      <phase-progress-bar :phase-progress-info="phaseProgressInfo" :cancel-info="cancelInfo" />
    </a-spin>
    <a-space class="record-title">
      <e-icon type="records" font-size="16px" />
      <span>Phase Records</span>
      <a-divider v-if="revivalClient && revivalExpiryDate" type="vertical" />
      <span v-if="revivalClient && revivalExpiryDate" style="font-weight: normal; font-size: 14px">
        Expiry Date: {{ revivalExpiryDate }}
      </span>
      <a-divider v-if="revivalClient" type="vertical" />
      <a-button v-if="revivalClient" type="link" @click="handleTerminate">
        <a-space>
          <e-icon type="trunoff" font-size="16px" />
          <span>Terminate</span>
        </a-space>
      </a-button>
    </a-space>
    <a-divider />
    <a-spin :spinning="processLoading" v-permission="'PhaseProgress:Query'">
      <div style="min-height: 200px">
        <dead-reason v-if="cancelInfo !== null && Object.keys(cancelInfo).length > 0" :record="cancelInfo" />
        <touch-record
          v-for="(record, index) in touchRecords"
          :key="record.id"
          :editable="leadStatus === 0 && index === 0"
          :client-id="id"
          :lead-id="leadId"
          :record="record"
          :download-handler="downloadHandler"
        />
        <e-empty v-if="touchRecords.length === 0" style="text-align: center">
          <template #description> <div style="color: #6b798e; text-align: center">No Phase Record</div> </template>
        </e-empty>
      </div>
    </a-spin>
    <a-modal
      v-model:visible="showReasonModal"
      :footer="cantTransitReasons.length > 0 && isAllow === true ? undefined : null"
      ok-text="Ignore Warning Items"
      width="536px"
      :title="isAllow ? 'Warning' : 'Operation Failure'"
      wrap-class-name="primary-modal no-padding"
      @ok="handleTransit(true)"
    >
      <span v-if="!isAllow" class="tips">Need to add more information :</span>
      <div v-for="reason in cantTransitReasons" :key="reason.id" class="block basic-info">
        <span class="title">{{ reason.name }}</span>
        <div class="group">
          <div v-for="(item, index) in reason.resonList" :key="index" class="reason">
            <a-space>
              <e-icon :type="item.level === 0 ? 'error1' : 'tips1'" :color="item.level === 0 ? '#fc4b3b' : '#FFA724'" />
              {{ item.itemName }}
            </a-space>
          </div>
        </div>
      </div>
      <div v-if="Array.isArray(cantTransitContact) && cantTransitContact.length > 0" class="block contact">
        <span class="title">Contact</span>
        <div v-for="(contactInfo, index) in cantTransitContact" :key="index" class="group">
          <div class="name">
            <a
              target="_blank"
              :href="
                router.resolve({ name: 'Contact Edit', params: { id: id, contactId: contactInfo.id, action: 'edit' } })
                  .href + '#auto-close'
              "
            >
              {{ contactInfo.contactName }}
            </a>
          </div>
          <div v-for="(reason, subIndex) in contactInfo.contactResonList" :key="subIndex" class="reason">
            <a-space><e-icon type="error1" color="#fc4b3b" /> {{ reason }}</a-space>
          </div>
          <a-divider dashed />
        </div>
      </div>
    </a-modal>
  </e-container>
  <terminate-reason v-model:show="showTerminateReason" :client-id="id" />
</template>

<script setup>
import { computed, ref, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import EContainer from '@/components/EContainer.vue'
import ETitle from '@/components/ETitle.vue'
import EIcon from '@/components/EIcon.vue'
import PhaseProgressBar from '@/pages/Client/components/ProgressBar.vue'
import PhaseProgress from '@/api/client/phaseProgress.js'
import TouchRecord from '@/pages/Client/components/TouchRecord.vue'
import DeadReason from '@/pages/Client/components/DeadReason.vue'
import TerminateReason from './phaseProgress/terminateReason.vue'
import useDownload from '@/hooks/useDownload.js'
import EEmpty from '@/components/EEmpty.vue'
import { CONFIRM_BACK_TO_DETAIL } from '@/constants/message.js'
const { Modal } = inject('Feedback')
const route = useRoute()
const router = useRouter()
const store = useStore()
const emits = defineEmits(['updated'])
// 下载器
const downloadHandler = useDownload
const processLoading = ref(true)
// 客户 id
const id = route.params.id
// 客户简要信息（是否活跃、是否是目标客户，是否可以转正等）
const briefInfo = computed(() => store.state.client.briefInfo)
// phase 0用户
const clientIsNoPhase = computed(() => !briefInfo.value.isExisting && briefInfo.value.phaseID === -1)
// 是二次开发
const revivalClient = computed(() => briefInfo.value.reconnectStatus >= 20)
// 是二次开发但是还未restart
const revivalClientNeedRestart = computed(() => briefInfo.value.reconnectStatus === 20)
// 二次开发过期时间
const revivalExpiryDate = ref(null)
// 线索id leadIdForMenu Menu组件需要数组形数据
const leadId = ref(null)
const leadIdForMenu = computed({
  get: () => {
    return [leadId.value]
  },
  set: val => {
    leadId.value = val[0]
  }
})
// 线索状态 1:不活跃的 2:活跃的
const leadStatus = ref(1)
// 全部线索
const leads = ref([{ value: -1 }])
// phase 信息，用于进度显示
const phaseProgressInfo = ref([])
// 联系记录
const touchRecords = ref([])
// 取消信息
const cancelInfo = ref({})
// 是否具备基础转正条件
const canTransit = ref(false)
store.dispatch('dict/getCommunicationMethods')
store.dispatch('dict/getCommunicationCategories')
// 获取当前客户的所有线索
PhaseProgress.getLeadsRecords(id).then(res => {
  leads.value = res.data
  // 如果不是Phase 0客户
  if (!clientIsNoPhase.value && !revivalClientNeedRestart.value) {
    // 查看是否可以转正
    checkClientIsCanTransit()
    if (Array.isArray(leads.value) && leads.value.length > 0) {
      leadId.value = leads.value[0].value
      leadStatus.value = leads.value[0].status
      // 默认加载第一条线索
      loadLeadData(leadId.value)
    } else {
      processLoading.value = false
    }
  } else {
    // Phase 0用户显示激活视图
    processLoading.value = false
    cancelInfo.value = null
    leadId.value = -1
  }
})
// 查看客户是否具备基础转正条件
const checkClientIsCanTransit = () => {
  PhaseProgress.isCanTransit(id).then(({ data }) => {
    canTransit.value = data
  })
}
// 加载线索信息
const loadLeadData = leadId => {
  PhaseProgress.getLeadPhase(leadId).then(res => {
    phaseProgressInfo.value = res.data
    PhaseProgress.getTouchRecords(id, leadId)
      .then(res => {
        revivalExpiryDate.value = res.data.expiryDate
        touchRecords.value = res.data.phaseRecords
        cancelInfo.value = res.data.leadsInfo
        if (Array.isArray(touchRecords.value)) touchRecords.value.reverse()
        emits('updated')
      })
      .finally(() => {
        processLoading.value = false
      })
  })
}
// 监听增加记录
const handleProgressUpdated = () => {
  checkClientIsCanTransit()
  PhaseProgress.getLeadsRecords(id).then(res => {
    leads.value = res.data
    leadId.value = leads.value[0].value
    leadStatus.value = leads.value[0].status
    loadLeadData(leadId.value)
  })
}
// 监听改变线索
const handleChangeLead = ({ item, key }) => {
  if (key !== leadId.value) {
    leadStatus.value = item.status
    leadId.value = key
    if (key > 0) {
      processLoading.value = true
      loadLeadData(leadId.value)
    } else {
      // 有一条 id为-1的线索，代表激活视图
      cancelInfo.value = null
      touchRecords.value = []
    }
  }
}
// 终止二次开发
const showTerminateReason = ref(false)
const handleTerminate = () => {
  showTerminateReason.value = true
}
// 转正按钮
const showReasonModal = ref(false)
const isAllow = ref(false)
const cantTransitReasons = ref([])
const cantTransitContact = ref([])
const handleTransit = (ignoreWarning = false) => {
  PhaseProgress.isAllowTransit(id).then(({ data }) => {
    if (
      !data.isAllow ||
      (Array.isArray(data.transitFailResons) && data.transitFailResons.length > 0 && !ignoreWarning)
    ) {
      isAllow.value = data.isAllow
      showReasonModal.value = true
      cantTransitReasons.value = data.transitFailResons
      cantTransitContact.value = data.contactFailResons
    } else {
      showReasonModal.value = false
      PhaseProgress.transit(id).then(({ data }) => {
        setTimeout(() => {
          handleProgressUpdated()
        }, 3000)
        window.open(data)
      })
    }
  })
}
</script>

<style lang="less" scoped>
.operations {
  display: flex;
  justify-content: space-between;
}
.activate-client {
  width: 100%;
  height: 93px;
  background-color: @phase-default;
  margin: 24px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  .ant-tag {
    padding: 6px 16px;
    font-size: 14px;
    font-weight: bold;
    background-color: #d9cfcf;
    color: #979191;
    border-color: #beb7b7;
    &.revival {
      background-color: #61bb99;
      color: #ffffff;
      border-color: #61bb99;
    }
  }
  :deep(.ant-space-item) {
    font-weight: bold;
  }
}
.record-title {
  color: @text-gray;
  font-size: 16px;
  font-weight: bold;
}
</style>
<style lang="less">
.no-padding {
  .ant-modal-body {
    padding: 0 0 48px 0 !important;
    .tips {
      display: inline-block;
      padding: 24px 24px 0 24px;
    }
    .block {
      margin-left: 80px;
      padding: 24px 0;
      border-bottom: 1px solid @border-color;
      .title {
        display: inline-block;
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 24px;
      }
      .group {
        .reason {
          margin-top: 16px;
        }
        &:last-child {
          .ant-divider {
            display: none;
          }
        }
      }
    }
  }
}
</style>
<route lang="yaml">
name: Phase Progress
path: '/client/:id/phase-progress'
meta:
  sort: 40
  title: Phase Progress
  icon: Phase_Progress
  permission: PhaseProgress
</route>
